import Vue from 'vue'
import VueRouter from 'vue-router'
// import Home from '../views/Home.vue'

Vue.use(VueRouter)
//路由嵌套
const routes = [
  {
    path: '/Home',
    name: 'zhuye',
    component: () => import(/* webpackChunkName: "Home" */'../pages/Home'),
    meta: {title: '主页'},  //meta用来给路由进行权限判断或赋值
    children: [  //用过children配置子级路由
      {
        path: 'news', //此处一定不要写:/
        name: 'xinwen',
        component: () => import(/* webpackChunkName: "Home" */'../pages/News'),
        meta: {isAuth: true, title: "新闻"}
      },
      {
        path: 'message',
        name: 'xiaoxi',  //给路由命名
        component: () => import(/* webpackChunkName: "Home" */'../pages/Message'),
        meta: {isAuth: true, title: '消息'},

        //前置局部、独享路由守卫 某一个路由独享 没有后置 只有一个
        beforeEnter: (to,from,next) => {
          if(to.meta.isAuth){  //判断当前路由是否需要进行权限控制
            if (localStorage.getItem('school') === '衡阳技师学院') {  //权限控制的具体规则
              next()  //放行
            }else {
              alert('学校名不对，无权限查看')
            }
          }else {
            console.log('鉴权失败，无权限查看')
            next();  //放行
          }
        },
        children: [  //用过children配置子级路由
          {
            path: 'detail',
            name: 'Particulars',
            meta: {isAuth: true, title: '详情'},
            component: () => import(/* webpackChunkName: "Home" */'../pages/Detail'),
            props({query: {id, title}}) {
              return {id, title}
            }
          },
        ]
      }
    ]
  },
  {
    path: '/about',
    name: 'About',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../pages/About'),
    meta: {title: '关于',isAuth:true},
  }
]

const router = new VueRouter({
  routes,
  mode:'history'
})
//全局潜质路由守卫——初始化的时候被调用、每次路由切换之前被调用 记住还有独享的路由守卫但是只有前置

router.beforeEach((to,from,next)=>{
  console.log(to,from)
  //to.path==='/home/message'
  /*第一种配置方式
  if(to.name === 'xinwen' || to.name==='xiaoxi') {
    if (localStorage.getItem('school') === '衡阳技师学院') {
      next()
    }else {
      alert('学校名不对，无权限查看')
    }
  }else {
    next();
  }
*/
  //第二种方式 使用meta:{isAuth:true or false} 是否鉴权
  if(to.meta.isAuth){  //判断当前路由是否需要进行权限控制
    if (localStorage.getItem('school') === '衡阳技师学院') {  //权限控制的具体规则
      next()  //放行
    }else {
      alert('学校名不对，无权限查看')
    }
  }else {
    console.log('鉴权失败，无权限查看')
     next();  //放行
  }
})

//全局后置路由守卫——初始化的时候被调用、每次路由切换之后被调用
router.afterEach((to,from) => {
  document.title = to.meta.title || '主页展示'  //修改网页的title
  console.log(from)
})
export default router
